package controller

import (
	"bytes"
	"encoding/json"
	"fmt"
	"hook/models"
	"hook/models/config"
	"net/http"

	"github.com/gin-gonic/gin"
)

type HookController struct {
}

func (con *HookController) Hook(c *gin.Context) {
	id := c.Param("id")

	var gogsStruct models.GogsStruct
	c.Bind(&gogsStruct)

	var feishu models.FeishuStruct
	var tags []models.FeishuTag
	tags = append(tags, models.FeishuTag{
		Tag: "text",
		Text: fmt.Sprintf(`
		 %s 仓库已更新
		 更新日志: %s
		 更新时间: %s
		 更新人: %s`,
			gogsStruct.Repository.FullName,
			gogsStruct.Commits[0].Message,
			gogsStruct.Repository.UpdateAt.Local().Format("2006-01-02 15:04:05"),
			gogsStruct.Commits[0].Commiter.Name),
	}, models.FeishuTag{
		Tag:  "a",
		Text: "查看更新内容",
		Href: gogsStruct.Commits[0].Url,
	})
	feishu.MsgType = "post"
	feishu.Content = make(map[string]map[string]models.FeishuContent)
	feishu.Content["post"] = make(map[string]models.FeishuContent)
	feishu.Content["post"]["zh_cn"] = models.FeishuContent{
		Title:   "Git更新通知",
		Content: [][]models.FeishuTag{tags},
	}

	bytesData, _ := json.Marshal(feishu)
	fmt.Println(string(bytesData))
	client := http.DefaultClient
	res, err := client.Post(config.Cfg.Hook+id, "application/json;charset=utf-8", bytes.NewBuffer([]byte(bytesData)))
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
	}
	defer res.Body.Close()
	decoder := json.NewDecoder(res.Body)
	body := make(map[string]any)
	err = decoder.Decode(&body)
	fmt.Println(err, body)
}
